﻿#!/usr/bin/env python

import sys

app_path='C:/Archive/Maaref/Development/title/'
data_path = 'data/'
sys.path.append(app_path+'include')

#from sitecustomize import *

#sys.setappdefaultencoding("utf-8")

from PyQt4 import QtCore, QtGui, QtSql

from apiHelper import info
from myobjects import *

from addNewDocument import NewDocumentWindow



class FileList(QtGui.QListWidget):
	def __init__(self,parent=None,mw=None):
		QtGui.QListWidget.__init__(self,parent)
		self.setMinimumWidth(50)
		self.setMaximumWidth(250)
		self.setMinimumHeight(50)
		self.setMaximumHeight(150)
		QtCore.QObject.connect(self, QtCore.SIGNAL("currentRowChanged (int)") ,self.documentSelected)		

		self.mw = mw
		
	def fillList(self):

		self.docs = self.mw.rootTitle.documents
		self.clear
		for doc in self.docs:
			self.addItem(doc.name)	

	def documentSelected(self,row):
		self.mw.currentDoc = self.docs[row]
		f = open(self.mw.currentDoc.path,"rb")
		lines = f.readlines()
		all = "".join(lines)
		f.close()
		s = u"<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head>" + all;
		self.mw.editor.setHtml(s)
			

class TitleTree(QtGui.QTreeWidget):
	def __init__(self,parent=None,mw=None):
		QtGui.QTreeWidget.__init__(self,parent)
		
		self.setMinimumWidth(50)
		self.setMaximumWidth(250)
		self.setColumnCount(1)

		self.createActions()
		
#		self.setMouseTracking(True)
#		QtCore.QObject.connect(self,QtCore.SIGNAL("itemEntered(QTreeWidgetItem,int)"),self.treeEntered)
		self.setAcceptDrops(False)
		self.setDragEnabled(False)
		self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
		self.setDropIndicatorShown(False)
		self.mw = mw
	
	def createActions(self):
		self.delAct = QtGui.QAction(u"&حذف", self)
		self.delAct.setShortcut(self.tr("Ctrl+d"))
		self.connect(self.delAct, QtCore.SIGNAL("triggered()"), self.deleteCurrent)

		self.insAct = QtGui.QAction(u"&اضافه", self)
		self.insAct.setShortcut(self.tr("Ctrl+f"))
		self.connect(self.insAct, QtCore.SIGNAL("triggered()"), self.insertAfter)

		self.insChildAct = QtGui.QAction(u"&زير عنوان جديد", self)
		self.insChildAct.setShortcut(self.tr("Ctrl+g"))
		self.connect(self.insChildAct, QtCore.SIGNAL("triggered()"), self.insertChild)

		self.renameAct = QtGui.QAction(u"&تغيير عنوان", self)
		self.renameAct.setShortcut(self.tr("Ctrl+h"))
		self.connect(self.renameAct, QtCore.SIGNAL("triggered()"), self.renameTitle)

		self.cutAct = QtGui.QAction(u"&انتقال از",self)
		self.cutAct.setShortcut(self.tr("Ctrl+x"))
		self.connect(self.cutAct,QtCore.SIGNAL("triggered()"),self.cutTitle)

		self.pasteAct = QtGui.QAction(u"&انتقال به",self)
		self.pasteAct.setShortcut(self.tr("Ctrl+v"))
		self.connect(self.pasteAct,QtCore.SIGNAL("triggered()"),self.pasteTitle)


		self.cmenu = QtGui.QMenu(self)
		self.cmenu.addAction(self.delAct)
		self.cmenu.addAction(self.insAct)
		self.cmenu.addAction(self.insChildAct)
		self.cmenu.addAction(self.renameAct)
		self.cmenu.addAction(self.cutAct)
		self.cmenu.addAction(self.pasteAct)


		QtCore.QObject.connect(self,QtCore.SIGNAL("itemSelectionChanged()"),self.titleSelected)

        def titleSelected(self):
		s = " "
		try:
	                s = self.sections[list(self.selectedItems())[0]]	
			f = open(s.file_path(),"rb")
			lines = f.readlines()
			f.close()
			s = u"<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body dir=rtl>" + "".join(lines);
			self.mw.sectionEditor.setHtml(s)
		except:
			self.mw.sectionEditor.clear()

	
	def cutTitle(self):
		self.cuttedItem = self.sections[list(self.selectedItems())[0]]
	
	def pasteTitle(self):
		metadata.engine.echo = True
		if self.cuttedItem != None :
			s = self.sections[list(self.selectedItems())[0]]
			db.connect().execute("update section set _index=_index+1 where parent_id=%d and _index>%d" % (s.parent_id,s._index))
			self.cuttedItem.parent_id = s.parent_id
			self.cuttedItem._index = s._index + 1
			session.flush()
			self.mw.reloadTree()
			self.fillTree()
			self.cuttedItem = None
		metadata.engine.echo = False	

	def deleteCurrent(self):
		s = self.sections[list(self.selectedItems())[0]]	
		if s.parent_id==102:
			s.parent_id = -1
		else:
			s.parent_id = 102
		session.flush()
		self.mw.reloadTree()
		self.fillTree()


	def insertAfter(self):
		answer = False
		x = QtGui.QInputDialog.getText(self,u"نام عنوان جديد",u"عنوان جديد:")
		newName = "%s" % x[0]
		answer = x[1]
		if(answer):
			s = self.sections[list(self.selectedItems())[0]]	
			db.connect().execute("update section set _index=_index+1 where parent_id=%d and _index>%d" % (s.parent_id,s._index))
			se = Section()
			se._index=s._index+1
			se.parent_id=s.parent_id
			se.name=newName
			session.save(se)
			session.flush()
			self.mw.reloadTree()
			self.fillTree()

	def insertChild(self):
		answer = False
		x = QtGui.QInputDialog.getText(self,u"نام عنوان جديد",u"عنوان جديد:")
		newName = "%s" % x[0]
		answer = x[1]
		if(answer):
			s = self.sections[list(self.selectedItems())[0]]	
			db.connect().execute("update section set _index=_index+1 where parent_id=%d " % s.parent_id)
			se = Section()
			se._index=0
			se.parent_id=s.id
			se.name=newName
			session.save(se)
			session.flush()
			self.mw.reloadTree()
			self.fillTree()


	def renameTitle(self):
		answer = False
		x = QtGui.QInputDialog.getText(self,u"نام عنوان جديد",u"عنوان جديد:")
		newName = unicode("%s" % x[0])
		answer = x[1]
		if(answer):
			s = self.sections[list(self.selectedItems())[0]]
			s.name = newName
			session.flush()
			self.mw.reloadTree()
			self.fillTree()


	def contextMenuEvent(self,event):
		self.cmenu.exec_(event.globalPos())
	
	def addSectionChilds(self,si,qtwi):
		for s in si.childs:
			tqtwi = QtGui.QTreeWidgetItem(qtwi)
			self.sections[tqtwi] = s
			tqtwi.setText(0,s.name)
			self.addSectionChilds(s,tqtwi)
	
	def treeEntered(self,q,i):
		print "tree enter"
		print q
		print i

	def fillTree(self):
		self.clear()
		self.mw.reloadTree()
		try:
			del self.sections
		except:
			pass
		self.sections = {}

		for sec in section_query.select(Section.c.parent_id==-1,order_by=[Section.c.parent_id,Section.c._index]):
			tqtwi = QtGui.QTreeWidgetItem(self)			
			self.sections[tqtwi] = sec
			tqtwi.setText(0,sec.name)
			self.addSectionChilds(sec,tqtwi)
		
#		tqtwi = QtGui.QTreeWidgetItem(self)
#		self.sections[tqtwi] = self.mw.recycle
#		tqtwi.setText(0,self.mw.recycle.name)
#		self.addSectionChilds(self.mw.recycle,tqtwi)

class Editor(QtGui.QTextBrowser):
	def __init__(self,parent=None,mw=None):
		QtGui.QTextBrowser.__init__(self,parent)
		self.setReadOnly(True)
		QtCore.QObject.connect(self, QtCore.SIGNAL("cursorPositionChanged()") ,self.docSelection)		
		self.mw = mw

	def keyPressEvent(self,event):
		if event.text()=="i":
			self.zoomIn(1)
		if event.text()=="o":
			self.zoomOut(1)

	def fill(self):
		pass

	def docSelection(self):
		c = self.textCursor()
		sds = documentTitle_query.select(and_(DocumentTitle.c.document_id==self.mw.currentDoc.id,and_(DocumentTitle.c.start_pos<c.selectionStart(),DocumentTitle.c.end_pos>c.selectionEnd())))
		self.mw.debugger.clear()
		for sd in sds[:]:
			c.setPosition(sd.start_pos)
			c.movePosition(QtGui.QTextCursor.Left,QtGui.QTextCursor.KeepAnchor,sd.end_pos - sd.start_pos+1)
			self.mw.debugger.insertPlainText(sd.section.completePath()+"\n")
		if (len(sds)==0):
			self.mw.debugger.insertPlainText(u"هيج عنواني موجود نيست");


class SectionEditor(QtGui.QTextBrowser):
	def __init__(self,parent=None,mw=None):
		QtGui.QTextBrowser.__init__(self,parent)
		self.setReadOnly(False)
		self.mw = mw


class MainWindow(QtGui.QMainWindow):
        def assignTitle(self):
            if (QtGui.QMessageBox.question(self,u"عناوين",
                                           u"آيا از انتساب عنوان به اين قسمت از متن مطمئن هستيد؟",
                                           QtGui.QMessageBox.Yes,QtGui.QMessageBox.No,QtGui.QMessageBox.NoButton)==QtGui.QMessageBox.Yes):
                c = self.editor.textCursor()
		s = self.titles.sections[list(self.titles.selectedItems())[0]]
		sd = DocumentTitle()
		sd.section_id = s.id
		sd.document_id=self.currentDoc.id
		sd.start_pos=c.selectionStart()
		sd.end_pos=c.selectionEnd()
		sd.comment = " "
		session.save(sd)
		session.flush()


	def saveDocument(self):
		self.statusBar().showMessage(u'ذخيره سازي در %s' % self.titles.sections[list(self.titles.selectedItems())[0]].file_path())
		
		f = QtCore.QFile(self.titles.sections[list(self.titles.selectedItems())[0]].file_path())
		f.open(QtCore.QIODevice.WriteOnly)
		f.write(self.sectionEditor.toHtml().toUtf8())
		f.close()
		
	
	def x(self):
		sys.exit()
	
	def addNewDoc(self):
		self.new_document_name = " "
		self.new_document_path = " "
		n = NewDocumentWindow(self,self) 
		if(n.exec_()==1):
			d = Document()
			d.name=self.new_document_name
			d.path=self.new_document_path
			d.section_id=self.rootTitle.id
			session.save(d)		
			session.flush()
			self.reloadTree()
			self.fileList.fillList()


	def reloadTree(self):
		
		session.clear()
		session.close()
		section_query = session.query(Section)
		document_query = session.query(Document)
		documentTitle_query = session.query(DocumentTitle)

		self.recycle = section_query.select(Section.c.id==102,order_by=[Section.c.parent_id,Section.c._index])[0]
		self.rootTitle = section_query.select(Section.c.id==104,order_by=[Section.c.parent_id,Section.c._index])[0]


	def __init__(self,parent=None):
		
		QtGui.QMainWindow.__init__(self,parent)
		
		self.reloadTree()

		self.currentDoc = None
		self.currentTitle = None

		self.editor = Editor(mw=self)
		self.sectionEditor = SectionEditor(mw=self)
		self.sectionEditor.setMaximumHeight(100)

		self.debugger = QtGui.QTextEdit(self)
		self.debugger.setAcceptRichText(False)
		self.debugger.setMaximumHeight(50)

		self.titles = TitleTree(mw=self)
		self.fileList = FileList(mw=self)

		self.saveButton = QtGui.QPushButton(u'&ذخيره')
		self.saveButton.setMaximumWidth(100)
		self.saveButton.setMinimumHeight(100)
		QtCore.QObject.connect(self.saveButton,QtCore.SIGNAL("clicked()"),self.saveDocument)

                self.assignButton = QtGui.QPushButton(u'&انتساب')
                self.assignButton.setMaximumHeight(40)
                QtCore.QObject.connect(self.assignButton,QtCore.SIGNAL("clicked()"),self.assignTitle)
		
		exitAction = QtGui.QAction(QtGui.QIcon('images/sout.gif'),u'&خروج',self)
		exitAction.setShortcut('Ctrl+X')
		exitAction.setStatusTip(u'خروج از برنامه')
		QtCore.QObject.connect(exitAction,QtCore.SIGNAL("triggered()"),self.x)

		newDocumentAction = QtGui.QAction(QtGui.QIcon('images/addNew.gif'),u'&مستند جديد',self)
		newDocumentAction.setShortcut('Ctrl+I')
		newDocumentAction.setStatusTip(u'افزودن مستند جديد')
		QtCore.QObject.connect(newDocumentAction,QtCore.SIGNAL("triggered()"),self.addNewDoc)

		fileMenu = self.menuBar().addMenu(u'&فايل')
		fileMenu.addAction(newDocumentAction)
		fileMenu.addSeparator()
		fileMenu.addAction(exitAction)

                titleControl = QtGui.QHBoxLayout()
                titleControl.addWidget(self.assignButton)

		rLayout = QtGui.QVBoxLayout()
		rLayout.addWidget(self.fileList)
		rLayout.addWidget(self.titles)
		rLayout.addLayout(titleControl)
		
		controlLayout  = QtGui.QHBoxLayout()
		controlLayout.addWidget(self.sectionEditor)
		controlLayout.addWidget(self.saveButton)

		lLayout = QtGui.QVBoxLayout()
		lLayout.addWidget(self.editor)
		lLayout.addLayout(controlLayout)
		lLayout.addWidget(self.debugger)

		
		mLayout = QtGui.QHBoxLayout()
		mLayout.addLayout(rLayout)
		mLayout.addLayout(lLayout)
		
		self.panel = QtGui.QFrame()
		self.panel.setFrameShape(QtGui.QFrame.StyledPanel)
		self.panel.setFrameStyle(QtGui.QFrame.Raised)
		self.panel.setLayout(mLayout)
		
		self.setCentralWidget(self.panel)
		self.setWindowTitle(u"عناوين")
		

		self.titles.fillTree()
		self.editor.fill()
		self.fileList.fillList()

		self.setWindowOpacity(1)
		self.setWindowState(QtCore.Qt.WindowMaximized);

if __name__ == "__main__":
#    info (QtCore)
#    info(MainWindow)

    app = QtGui.QApplication(sys.argv)
    app.setLayoutDirection(QtCore.Qt.RightToLeft)
    
    splashScreen = QtGui.QSplashScreen(QtGui.QPixmap('images/splash.png'))
    splashScreen.setWindowOpacity(0.7)
    splashScreen.show()
    
    window = MainWindow()
    window.show()
    
    splashScreen.finish(window)
    
    sys.exit(app.exec_())    		
